package com.chookss.tiku;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.HomeActivityss;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.NavigationBaseActivity;
import com.chookss.tiku.entity.AnswerRecord;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.view.BasisTimesUtils;
import com.chookss.view.DrawableTextView;
import com.chookss.view.RecycleViewDivider;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.Nullable;
import per.wsj.library.AndRatingBar;

@SuppressLint("ValidFragment")
public class ExamRecordFragment extends Fragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.tvDate)
    DrawableTextView tvDate;
    @BindView(R.id.tvAll)
    TextView tvAll;
    @BindView(R.id.llDate)
    LinearLayout llDate;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.tvNone2)
    TextView tvNone2;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llNoneInit)
    LinearLayout llNoneInit;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;

    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String recordType = "";//  1 智能 2 练习 3 模拟卷4考试
    private String periodName = "202105";
    private List<AnswerRecord> list = new ArrayList<>();
    private ExamRecordAdapter adapter;

    public ExamRecordFragment(String recordType) {
        this.recordType = recordType;
    }

    public ExamRecordFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_exam_record, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {

        if("5".equals(recordType)){
            tvNone.setText("暂无背题记录");
            String str = "快去<font color='#E12416'>背题</font>吧！";
            tvNone2.setText(Html.fromHtml(str));
        }else{
            String str = "快去<font color='#E12416'>答题练习</font>吧！";
            tvNone2.setText(Html.fromHtml(str));
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date date = new Date(System.currentTimeMillis());
        String time = simpleDateFormat.format(date);
        tvDate.setText(time);
        periodName = time.replace("-", "");
        rvView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rvView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        adapter = new ExamRecordAdapter(R.layout.item_answer_record, mContext, list);
        rvView.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@io.reactivex.annotations.NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        tvDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickDialog(tvDate.getText().toString());
            }
        });
        llNoneInit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=null;
                if ("1".equals(recordType)) {
                    intent = new Intent(mContext, PracticeTestActivity.class);
                    intent.putExtra("practiceType", "1");
                    startActivity(intent);
                } else if ("2".equals(recordType)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        intent = new Intent(mContext, SelectPracticeCatalog.class);
                        startActivity(intent);
                    }
                } else if ("3".equals(recordType)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        intent = new Intent(mContext, SelectSimulationCatalog.class);
                        startActivity(intent);
                    }

                } else if ("4".equals(recordType)) {
                    if (PermissionSpUtils.getBoolean(mContext,"05",false)) {
                        String code1 = new ShareUtils().getString(mContext, StaticClass.BOTTOM_1_CODE, "");
                        String code3 = new ShareUtils().getString(mContext, StaticClass.BOTTOM_3_CODE, "");
                        if ("05".equals(code1) || "05".equals(code3)) {
                            intent = new Intent(mContext, HomeActivityss.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                            Map<String,String> map=new HashMap<>();
                            map.put("HomeBottom","Kaoshi");
                            map.put("code","05");
                            EventBus.getDefault().post(new MyEvent(map));
                            EventBus.getDefault().post(new MyEvent("Web_Close"));
                        } else {
                            intent = new Intent(mContext, NavigationBaseActivity.class);
                            intent.putExtra("type",5);
                            mContext.startActivity(intent);
                        }

                    } else {
                        MyToast.show("管理员已关闭考试功能");
                    }
                } else {
                    intent = new Intent(mContext, PracticeTestActivity.class);
                    intent.putExtra("practiceType", "1");
                    startActivity(intent);
                }
            }
        });
        getData();
    }

    int mYear = 0, mMonth = 0, mDay = 0;

    private void showDatePickDialog(String curDate) {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mYear == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(mContext, true, "请选择日期", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear = year;
                        mMonth = month - 1;
                        mDay = dayOfMonth;
                        if (month > 9) {
                            tvDate.setText(year + "-" + month);
                            periodName = year + "" + month;
                        } else {
                            tvDate.setText(year + "-0" + month);
                            periodName = year + "0" + month;
                        }
                        currentPage = 1;
                        isEnd = false;
                        getData();
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDayGone();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("recordType", recordType);
        map.put("periodName", periodName);
        map.put("pageSize", pageSize);
        map.put("pageNum", currentPage + "");
        MyHttpRequest.postRequest(Urls.getMyAnswerRecord, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {

                loadEnd();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        if (currentPage == 1) {
                            list.clear();
                            adapter.notifyDataSetChanged();
                        }
                        if(tvAll==null){
                            return;
                        }
                        tvAll.setText("共计" + jsonObject.getString("total") + "条");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            AnswerRecord answerRecord = new AnswerRecord();
                            answerRecord.createTime = jsonObject1.getString("createTime");
                            answerRecord.itemName = jsonObject1.getString("itemName");
                            answerRecord.score = jsonObject1.getString("score");
                            answerRecord.rightRatio = jsonObject1.getString("rightRatio");
                            answerRecord.totalNum = jsonObject1.getString("totalNum");
                            answerRecord.recordType = jsonObject1.getString("recordType");
                            answerRecord.itemCode = jsonObject1.getString("itemCode");
                            answerRecord.avgHard = jsonObject1.getString("avgHard");
                            answerRecord.periodName = jsonObject1.getString("periodName");
                            answerRecord.rank = jsonObject1.getString("rank");
                            answerRecord.rightNum = jsonObject1.getString("rightNum");
                            answerRecord.pmKey = jsonObject1.getString("pmKey");
                            list.add(answerRecord);
                        }
                        if(srlView==null||llNone==null){
                            return;
                        }
                        if (jsonArray.length() > 0) {
                            adapter.notifyDataSetChanged();
                            srlView.setVisibility(View.VISIBLE);
//                            llDate.setVisibility(View.VISIBLE);
                            llNone.setVisibility(View.GONE);
                        } else {
                            isEnd = true;
                            if (list.size() == 0) {
//                                llDate.setVisibility(View.GONE);
                                srlView.setVisibility(View.GONE);
                                llNone.setVisibility(View.VISIBLE);
                            }
                        }
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }


    class ExamRecordAdapter extends BaseQuickAdapter<AnswerRecord, BaseViewHolderEx> {
        private Context context;

        public ExamRecordAdapter(int layoutResId, Context context, @Nullable List<AnswerRecord> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, AnswerRecord item) {

            TextView tvType = helper.getView(R.id.tvType);
            TextView tvTypeTitle = helper.getView(R.id.tvTypeTitle);
            TextView tvDate = helper.getView(R.id.tvDate);
            AndRatingBar ratingBar = helper.getView(R.id.ratingBar);
            TextView tvSubject = helper.getView(R.id.tvSubject);
            TextView tvSubjectInit = helper.getView(R.id.tvSubjectInit);
            TextView tvTypeInit = helper.getView(R.id.tvTypeInit);
            TextView tvScore = helper.getView(R.id.tvScore);
            String recordType = item.recordType;
            if ("1".equals(recordType)) {
                tvType.setText("智");
                tvTypeTitle.setText("智能练习");
                tvTypeInit.setText("正确率：");
                tvSubjectInit.setText("答对题目：");
                tvScore.setText(ClearMoreZeroUtil.subZeroAndDot(item.rightRatio) + "%");
                tvScore.setTextColor(Color.parseColor("#FFAE00"));
                tvSubject.setText(Utils.changeNumber(item.rightNum) + "/" + Utils.changeNumber(item.totalNum) + "道");

            } else if ("2".equals(recordType)) {
                tvType.setText("专");
                tvTypeTitle.setText("专项练习");
                tvTypeInit.setText("正确率：");
                tvSubjectInit.setText("答对题目：");
                tvScore.setText(ClearMoreZeroUtil.subZeroAndDot(item.rightRatio) + "%");
                tvScore.setTextColor(Color.parseColor("#FFAE00"));
                tvSubject.setText(Utils.changeNumber(item.rightNum) + "/" + Utils.changeNumber(item.totalNum) + "道");

            } else if ("3".equals(recordType)) {
                tvType.setText("模");
                tvTypeTitle.setText("模拟卷-"+item.itemName);
                tvTypeInit.setText("正确率：");
                tvSubjectInit.setText("答对题目：");
                tvScore.setText(ClearMoreZeroUtil.subZeroAndDot(item.rightRatio) + "%");
                tvScore.setTextColor(Color.parseColor("#FFAE00"));
                tvSubject.setText(Utils.changeNumber(item.rightNum) + "/" + Utils.changeNumber(item.totalNum) + "道");

            } else if ("4".equals(recordType)) {
                tvType.setText("考");
                tvTypeTitle.setText("正式考试-"+item.itemName);
                tvTypeInit.setText("成绩：");
                tvSubjectInit.setText("答对题目：");
                tvScore.setText(ClearMoreZeroUtil.subZeroAndDot(item.score) + "分");
                tvScore.setTextColor(Color.parseColor("#6480F4"));
                tvSubject.setText(Utils.changeNumber(item.rightNum) + "/" + Utils.changeNumber(item.totalNum) + "道");

            } else if ("5".equals(recordType)) {
                tvType.setText("背");
                tvTypeTitle.setText("背题");
                tvTypeInit.setText("全站排名：");
                tvSubjectInit.setText("背题数量：");
                tvScore.setText(item.rank);
                tvScore.setTextColor(Color.parseColor("#F65679"));
                tvSubject.setText( Utils.changeNumber(item.totalNum) + "道");

            }
            ratingBar.setNumStars(5);
            if (Utils.isNull(item.avgHard)) {
                ratingBar.setRating(0);
            } else {
                ratingBar.setRating(Float.parseFloat(item.avgHard));
            }

            tvDate.setText(item.createTime);
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ExamResultActivitys.class);
                    intent.putExtra("recordType", item.recordType);
                    intent.putExtra("pmKey", item.pmKey);
                    intent.putExtra("examCode", item.itemCode);
                    intent.putExtra("examName", item.itemName);
                    startActivity(intent);
                }
            });
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

    }

}
